import Vue from 'vue';
import VueRouter from 'vue-router';
import Layout from '../views/Layout.vue';
import Store from '../store';

Vue.use(VueRouter);

const routes = [
  {
    path: '*',
    // 提示页
    component: () => import(/* webpackChunkName: "404" */ '../views/404')
  },
  {
    path: '/',
    // 提示页
    // 在阻止跳转时，需要写 from.path
    redirect: '/layout'
  },
  {
    path: '/layout',
    name: 'Layout',
    component: Layout,
    // 嵌套路由
    children: [
      {
        path: '/',
        component: () =>
          import(
            /* webpackChunkName: "kuCun" */
            '../components/tongJi/index.vue'
          )
      },
      {
        path: 'jinHuo',
        component: () =>
          import(
            /* webpackChunkName: "jinHuo" */
            '../components/jinHuo/index.vue'
          )
      },
      {
        path: 'xiaoHuo',
        component: () =>
          import(
            /* webpackChunkName: "xiaoHuo" */
            '../components/xiaoHuo/index.vue'
          )
      },
      {
        path: 'kuCun',
        component: () =>
          import(
            /* webpackChunkName: "kuCun" */
            '../components/kuCun/index.vue'
          )
      }
    ]
  },
  {
    path: '/user',
    name: 'User',
    component: () =>
      import(
        /* webpackChunkName: "login" */
        '../views/User.vue'
      )
  }
];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
});

// 做全局的路由拦截
router.beforeEach((to, from, next) => {
  var user = Store.state.users;
  if (to.path !== '/user' && !user.token && !user.loginState) {
    next('/user');
  } else if (to.path === '/user' && user.token && user.loginState) {
    next('/layout');
  } else {
    next();
  }
});

export default router;
